/*
 * Created by SharpDevelop.
 * User: agsd
 * Date: 09/02/2008
 * Time: 16:20
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Mogocal
{
	public sealed class NotificationIcon
	{
		private NotifyIcon notifyIcon;
		private ContextMenu notificationMenu;
        private service.EventRetriever eventRetriever;
        private ConfigurationSettings conf;
		private System.Windows.Forms.Timer timer;
		
		#region Initialize icon and menu
		public NotificationIcon()
		{
			notifyIcon = new NotifyIcon();
			notificationMenu = new ContextMenu(InitializeMenu());
		
			Stream s = File.OpenRead("mogocal.ico");
			notifyIcon.Icon = new Icon(s);
			
			notifyIcon.ContextMenu = notificationMenu;

			timer = new System.Windows.Forms.Timer();
			timer.Interval = 60000;
			timer.Tick += new EventHandler(timerTick);
			timer.Start();            
		}
		
		/// <summary>
		/// Occurs at timer tick
		/// </summary>
		void timerTick(object sender, EventArgs e)
		{
            if (conf == null)
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ConfigurationSettings));
                    StreamReader reader = new StreamReader(util.Util.getSettingsFileName());
                    conf = (ConfigurationSettings)serializer.Deserialize(reader);
                    reader.Close();

                    if ((conf.GoogleAccount == "") || (conf.GoogleAccountPassword == ""))
                    {
                        Config c = new Config();
                        timer.Stop();
                        if (c.ShowDialog() == DialogResult.OK)
                        {
                            
                            serializer = new XmlSerializer(typeof(ConfigurationSettings));
                            reader = new StreamReader(util.Util.getSettingsFileName());
                            conf = (ConfigurationSettings)serializer.Deserialize(reader);
                            reader.Close();

                            timer.Start();
                        }
                    }
                }
                catch (IOException)
                {
                    Config c = new Config();
                    if (c.ShowDialog() == DialogResult.OK)
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(ConfigurationSettings));
                        StreamReader reader = new StreamReader(util.Util.getSettingsFileName());
                        conf = (ConfigurationSettings)serializer.Deserialize(reader);
                        reader.Close();
                    }
                }

                catch (XmlException)
                {
                    util.Util.ShowMessageError("An error occcurred on xml configuration file loading.");
                }
            }
            
            eventRetriever = new service.EventRetriever(conf);

            try
            {
                eventRetriever.GetEvents();
            }
            catch (Google.GData.Client.InvalidCredentialsException credentialsException)
            {
                util.Util.ShowMessageError("Connection problem, please verify your google username and password. \n" + credentialsException.Message);
            }
            catch (Google.GData.Client.ClientQueryException queryException)
            {
                util.Util.ShowMessageError("Connection problem, please verify your network connection. \n" + queryException.Message);
            }
            catch (Google.GData.Client.GDataForbiddenException forbidenException)
            {
                util.Util.ShowMessageError("Connection problem, please verify your network connection. \n" + forbidenException.Message);
            }
            catch (Google.GData.Client.CaptchaRequiredException capchaException)
            {
                util.Util.ShowMessageError("Connection problem, please verify your network connection. \n" + capchaException.Message);
            }
		}
		
		private MenuItem[] InitializeMenu()
		{
			MenuItem[] menu = new MenuItem[] {
				new MenuItem("Configuration", menuConfigClick),
				new MenuItem("Exit", menuExitClick)
			};
			return menu;
		}
		#endregion
		
		#region Main - Program entry point
		/// <summary>Program entry point.</summary>
		/// <param name="args">Command Line Arguments</param>
		[STAThread]
		public static void Main(string[] args)
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			
			NotificationIcon notificationIcon = new NotificationIcon();
			notificationIcon.notifyIcon.Visible = true;
			Application.Run();			
		}
		#endregion
		
		#region Event Handlers

		private void menuConfigClick(object sender, EventArgs e)
		{
            Config c = new Config();
			timer.Stop();
             if (c.ShowDialog() == DialogResult.OK)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ConfigurationSettings));
                StreamReader reader = new StreamReader(util.Util.getSettingsFileName());
                conf = (ConfigurationSettings)serializer.Deserialize(reader);
                reader.Close();
				timer.Start();
            }
		}
		
		private void menuExitClick(object sender, EventArgs e)
		{			
			timer.Stop();
			timer.Dispose();
			
			notifyIcon.Dispose();
			
			Application.Exit();
		}		
		#endregion
	}
}
